package com.ruoyi.project.thirdservice.service.aliyun.logistics;

import com.alibaba.cloudapi.sdk.constant.SdkConstant;
import com.alibaba.cloudapi.sdk.model.ApiCallback;
import com.alibaba.cloudapi.sdk.model.ApiResponse;
import com.alibaba.cloudapi.sdk.model.HttpClientBuilderParams;
import com.alibaba.fastjson.JSON;
import com.ruoyi.project.thirdservice.service.aliyun.entity.logistics.AliyunLogisticsResp;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;

/**
 * @author yan
 */
@Service
@SuppressWarnings("all")
public class AliyunLogisticsTraceDispatchService {

    private static Logger logger = LoggerFactory.getLogger(AliyunLogisticsTraceDispatchService.class);

    private static final String DEFAULT_COMPANY = "auto";

    @Value("${aliyun.market.deliver.appKey}")
    private String APP_KEY;

    @Value("${aliyun.market.deliver.appSecret}")
    private String APP_SECRET;


    @PostConstruct
    public void setup() {
        //HTTP Client init
        HttpClientBuilderParams httpParam = new HttpClientBuilderParams();
        httpParam.setAppKey(APP_KEY);
        httpParam.setAppSecret(APP_SECRET);
        AliyunLogisticsHttpApiClient.getInstance().init(httpParam);


        //HTTPS Client init
        HttpClientBuilderParams httpsParam = new HttpClientBuilderParams();
        httpsParam.setAppKey(APP_KEY);
        httpsParam.setAppSecret(APP_SECRET);

        /**
         * HTTPS request use DO_NOT_VERIFY mode only for demo
         * Suggest verify for security
         */
        // httpsParam.setRegistry(getNoVerifyRegistry());

        AliyunLogisticsApiClient.getInstance().init(httpsParam);

        logger.info(">>> Aliyun logistics instance setup success!!");
    }

    /**
     * 异步的方式调用API
     *
     * @param logisticsNo
     * @param sendPhone
     * @param receiverPhone
     * @param callback
     */
    public void asyncQueryExpressNodeTrace(String logisticsNo, String sendPhone
            , String receiverPhone, ApiCallback callback) {
        AliyunLogisticsHttpApiClient.getInstance()
                .queryExpressNodeTrace(DEFAULT_COMPANY, logisticsNo, sendPhone, receiverPhone, callback);
    }

    /**
     * 同步的方式调用API
     *
     * @param logisticsNo
     * @param sendPhone
     * @param receiverPhone
     * @return
     */
    public AliyunLogisticsResp syncQueryExpressNodeTrace(String logisticsNo, String sendPhone, String receiverPhone) {
        ApiResponse response = AliyunLogisticsHttpApiClient.getInstance()
                .queryExpressNodeTraceSyncMode(DEFAULT_COMPANY, logisticsNo, sendPhone, receiverPhone);
        try {
            return JSON.parseObject(new String(response.getBody(),
                    SdkConstant.CLOUDAPI_ENCODING), AliyunLogisticsResp.class);
        } catch (Exception ex) {
            logger.error("Sync Query Express Node Trace Failed!!", ex);
            throw ex;
        }
    }

    public static void main(String[] args) {
        /*asyncQueryExpressNodeTrace("YT4532125168900", null, "15073152671", new ApiCallback() {
            @Override
            public void onFailure(ApiRequest request, Exception e) {
                logger.error("Async Query Express Node Trace Failed!!", e);
            }

            @Override
            public void onResponse(ApiRequest request, ApiResponse response) {
                try {
                    // 解析物流信息后存储
                    AliyunLogisticsResp data = JSON.
                            parseObject(new String(response.getBody(), SdkConstant.CLOUDAPI_ENCODING), AliyunLogisticsResp.class);
                    System.out.println(JSON.toJSONString(data));
                } catch (Exception ex) {
                    logger.error("Async Query Express Node Trace Failed!!", ex);
                }
            }
        });*/
    }
}
